package cn.bwq.datawebsocket.core.controller;

import cn.bwq.datawebsocket.core.server.WebSocketServer;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller("websocket_controller")
@RequestMapping("/api/ws")
public class HelloController {

    @GetMapping("/index/{sid}")
    public ModelAndView socket(@PathVariable("sid") String sid) {
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("sid", sid);
        return mv;
    }

    @ResponseBody
    @RequestMapping("/push/{sid}")
    public Map<String, Object> pushToWeb(@PathVariable("sid") String sid, @RequestParam("msg") String message) {
        Map<String, Object> result = new HashMap<>();
        if (message == null) {
            message = "这是一个空包";
        }
        try {
            WebSocketServer.sendInfo(message, sid);
            result.put("code", sid);
            result.put("msg", message);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
